var express = require('express');
var router = express.Router();
var request = require('request');

var user_data_control=require('../db_control/user_data_control');
var app_id = "你的id"
var app_secret = "你的secret"
var base_url = 'https://api.weixin.qq.com/sns/jscode2session'
var userid;

router.get('/',(req,res,next)=>{
  const code = req.query.code
  const url = `${base_url}?appid=${app_id}$secret=${app_secret}&js_code=${code}&grant_type=authorization_code`
  request(url,(error,res,body)=>{
    console.log('statusCode:',res?.statusCode);
    const theBody = JSON.parse(body);
    userid= theBody.openid
    console.log(theBody);
    res.end(body)
  })
})
router.post('/postUserInfo',(req,res,next)=>{
  const userData = {
    UnionId:userid,
    name:req.body.nickName,
    avatar:req.body.avatarUrl,
  }
  user_data_control.add_data(userData)
})

router.post('/verify',(req,res,next)=>{
  const base_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'
  const {appid,secret} = req.body
  request(`${base_url}&appid=${appid}&secret=${secret}`,(error,res,body)=>{
    console.log('statusCode:',res?.statusCode);
    const theBody = JSON.parse(body);
    const {access_token,expires_in}= theBody
    console.log(theBody);
    res.send({
      code:200,
      data:{
        access_token,
        expires_in
      }
    })
  })
})

module.exports = router;